package by.jabbby.service.listener;

import org.jivesoftware.smack.ConnectionListener;

import android.content.Intent;
import android.os.RemoteException;
import by.jabbby.Logger;
import by.jabbby.service.JabberService;
import by.jabbby.service.Status;

public class JabberConnectionListener implements ConnectionListener {
	JabberService js;

	public JabberConnectionListener(JabberService js) {
		this.js = js;
		Logger.i("JabberConnectionListener created");
	}

	public void connectionClosed() {
		try {
			js.getBinder().changeStatus(Status.OfLine.name());

			Intent intent = new Intent(JabberService.ACTION_CONNECTION_CLOSED);
			js.sendBroadcast(intent);
			Logger.i("JabberConnectionListener send broadCast: " + intent.getAction());
		} catch (RemoteException e) {
			Logger.e(e);
		}

	}

	public void connectionClosedOnError(Exception e) {
		Logger.e("Connection close with error: ", e);
		try {
			js.getBinder().changeStatus(Status.OfLine.name());

			
		} catch (RemoteException ee) {
			Logger.e(ee);
		}
		
		
		Intent intent = new Intent(JabberService.ACTION_CONNECTION_CLOSED_WITH_ERROR);
		js.sendBroadcast(intent);
		Logger.i("JabberConnectionListener send broadCast: " + intent.getAction());
	}

	public void reconnectingIn(int seconds) {
		Intent intent = new Intent(JabberService.ACTION_CONNECTION_RECONNECT_INSECOND);
		intent.putExtra(JabberService.ACTION_CONNECTION_RECONNECT_INSECOND, Integer.toString(seconds));
		js.sendBroadcast(intent);
		Logger.i("JabberConnectionListener send broadCast: " + intent.getAction());

	}

	public void reconnectionFailed(Exception e) {
		Intent intent = new Intent(JabberService.ACTION_CONNECTION_RECONNECT_FAILED);

		js.sendBroadcast(intent);
		Logger.i("JabberConnectionListener send broadCast: " + intent.getAction());
	}

	public void reconnectionSuccessful() {
		Intent intent = new Intent(JabberService.ACTION_CONNECTION_RECONNECT_SUCCESSFULL);

		js.sendBroadcast(intent);
		Logger.i("JabberConnectionListener send broadCast: " + intent.getAction());
	}

}
